package com.mychat.service.impl;


import com.mychat.entity.Constants;
import com.mychat.entity.dto.MessageSendDto;
import com.mychat.entity.dto.SysSettingDto;
import com.mychat.entity.dto.TokenUserInfoDto;
import com.mychat.entity.dto.UserContactSearchResultDto;
import com.mychat.entity.po.*;
import com.mychat.entity.query.*;
import com.mychat.enums.*;
import com.mychat.entity.vo.PaginationResultVO;
import com.mychat.exception.BusinessException;
import com.mychat.mappers.*;
import com.mychat.redis.RedisComponent;
import com.mychat.service.UserContactService;
import com.mychat.utils.CopyTools;
import com.mychat.utils.StringUtils;
import com.mychat.websocket.ChannelContextUtils;
import com.mychat.websocket.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:ServiceImpl
 * @auther:YYT
 * @date:2025/03/02
 */
@Service("userContactService")
public class UserContactServiceImpl implements UserContactService {

    @Resource
    private UserContactMapper<UserContact, UserContactQuery> userContactMapper;

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;
    @Resource
    private GroupInfoMapper<GroupInfo, GroupInfoQuery> groupInfoMapper;

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChatSessionMapper<ChatSession, ChatSessionQuery> chatSessionMapper;

    @Resource
    private ChatSessionUserMapper<ChatSessionUser, ChatSessionUserQuery> chatSessionUserMapper;

    @Resource
    private ChatMessageMapper<ChatMessage, ChatMessageQuery> chatMessageMapper;

    @Resource
    private MessageHandler messageHandler;

    @Resource
    private ChannelContextUtils channelContextUtils;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserContact> findListByParam(UserContactQuery query) {
        List<UserContact> list = this.userContactMapper.selectList(query);
        for (UserContact userContact : list) {
            System.out.println("Contact Name: " + userContact.getContactName()); // 打印 contactName
        }
        return list;
    }

    /**
     * 根据条件查询数量
     */
    @Override
    public Integer findCountByParam(UserContactQuery query) {
        return this.userContactMapper.selectCount(query);
    }

    /**
     * 分页查询
     */
    @Override
    public PaginationResultVO<UserContact> findListByPage(UserContactQuery query) {
        Integer count = this.findCountByParam(query);
        Integer pageSize = query.getPageSize() == null ? PageSize.SIZE15.getSize() : query.getPageSize();
        SimplePage page = new SimplePage(query.getPageNo(), count, pageSize);
        query.setSimplePage(page);
        List<UserContact> list = this.findListByParam(query);
        PaginationResultVO<UserContact> result = new PaginationResultVO<UserContact>(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserContact bean) {
        return this.userContactMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserContact> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userContactMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 根据UserIdAndContactId查询
     */
    @Override
    public UserContact getUserContactByUserIdAndContactId(String userId, String contactId) {
        return this.userContactMapper.selectByUserIdAndContactId(userId, contactId);
    }

    /**
     * 根据UserIdAndContactId更新
     */
    @Override
    public Integer updateUserContactByUserIdAndContactId(UserContact bean, String userId, String contactId) {
        return this.userContactMapper.updateByUserIdAndContactId(bean, userId, contactId);
    }

    /**
     * 根据UserIdAndContactId删除
     */
    @Override
    public Integer deleteUserContactByUserIdAndContactId(String userId, String contactId) {
        return this.userContactMapper.deleteByUserIdAndContactId(userId, contactId);
    }

    @Override
    public UserContactSearchResultDto searchContact(String userId, String contactId) {
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getEnumByPrefix(contactId.charAt(0) + "");
        if (typeEnum == null) {
            return null;
        }
        UserContactSearchResultDto resultDto = new UserContactSearchResultDto();
        switch (typeEnum) {
            case USER:
                UserInfo userInfo = userInfoMapper.selectByUserId(contactId);
                if (userInfo == null) {
                    return null;
                }
                resultDto = CopyTools.copy(userInfo, UserContactSearchResultDto.class);
                break;
            case GROUP:
                GroupInfo groupInfo = groupInfoMapper.selectByGroupId(contactId);
                if (groupInfo == null) {
                    return null;
                }
                resultDto.setNickName(groupInfo.getGroupName());
                break;
        }
        resultDto.setContactType(typeEnum.toString());
        resultDto.setContactId(contactId);

        if (userId.equals(contactId)) {
            resultDto.setStatus(UserContactStatusEnum.FRIEND.getCode());
            return resultDto;
        }

        UserContact userContact = this.userContactMapper.selectByUserIdAndContactId(userId, contactId);
        if (userContact != null) {
            resultDto.setStatus(userContact.getStatus());
            return resultDto;
        }
        return null;
    }

    @Override
    public List<UserContact> findGroupListByParam(UserContactQuery query) {
        return this.userContactMapper.selectGroupList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserContact(String userId, String contactId, UserContactStatusEnum userContactStatusEnum) {
        // 自己移除好友
        UserContact userContact = new UserContact();
        userContact.setStatus(userContactStatusEnum.getCode());
        userContactMapper.updateByUserIdAndContactId(userContact, userId, contactId);

        // 将好友中移除自己
        UserContact friendContact = new UserContact();
        if (userContactStatusEnum == UserContactStatusEnum.DELETED_BY_ME) {
            friendContact.setStatus(UserContactStatusEnum.DELETED_BY_FRIEND.getCode());
        } else if (userContactStatusEnum == UserContactStatusEnum.BLACK_BY_ME) {
            friendContact.setStatus(UserContactStatusEnum.BLACK_BY_FRIEND.getCode());
        }
        userContactMapper.updateByUserIdAndContactId(friendContact, contactId, userId);

        // 从我的好友列表中移除好友
        redisComponent.removeUserContact(contactId, userId);
        // 从好友的好友列表中移除自己
        redisComponent.removeUserContact(userId, contactId);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addContact(String applyUserId, String receiveUserId, String contactId, Integer contactType, String applyInfo) throws BusinessException {
        // 群聊人数
        if (UserContactTypeEnum.GROUP.getType().equals(contactType)) {
            UserContactQuery query = new UserContactQuery();
            query.setContactId(contactId);
            query.setContactType(UserContactTypeEnum.GROUP.getType());
            Integer count = this.userContactMapper.selectCount(query);
            SysSettingDto sysSettingDto = redisComponent.getSysSetting();
            if (count >= sysSettingDto.getMaxGroupMemberCount()) {
                throw new BusinessException("群聊人数已达上限");
            }
        }
        Date currentDate = new Date();
        // 同意,双方添加好友
        ArrayList<UserContact> contactList = new ArrayList<>();
        // 申请人添加对方
        UserContact userContact = new UserContact();
        userContact.setUserId(applyUserId);
        userContact.setContactId(contactId);
        userContact.setContactType(contactType);
        userContact.setStatus(UserContactStatusEnum.FRIEND.getCode());
        userContact.setCreateTime(currentDate);
        userContact.setLastUpdateTime(currentDate);
//		this.userContactMapper.insertOrUpdate(userContact); // 没问题
        contactList.add(userContact);

        // 如果是申请好友,接受人添加申请人,群组不用添加对方为好友
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            userContact = new UserContact();
            userContact.setUserId(receiveUserId);
            userContact.setContactId(applyUserId);
            userContact.setContactType(contactType);
            userContact.setStatus(UserContactStatusEnum.FRIEND.getCode());
            userContact.setCreateTime(currentDate);
            userContact.setLastUpdateTime(currentDate);
//			this.userContactMapper.insertOrUpdate(userContact);
            contactList.add(userContact);
        }
        this.userContactMapper.insertOrUpdateBatch(contactList);

        // 如果是好友,接收人也添加申请人为好友 添加缓存
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            redisComponent.addUserContact(receiveUserId, applyUserId);
        }
        redisComponent.addUserContact(applyUserId, contactId);

        // 创建会话
        String sessionId = null;
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            sessionId = StringUtils.getChatSessionId4User(new String[]{applyUserId, contactId});
        } else {
            sessionId = StringUtils.getChatSessionId4User(new String[]{contactId});
        }

        List<ChatSessionUser> chatSessionUserList = new ArrayList<>();
        if (UserContactTypeEnum.USER.getType().equals(contactType)) {
            ChatSession chatSession = new ChatSession();
            chatSession.setSessionId(sessionId);
            chatSession.setLastMessage(applyInfo);
            chatSession.setLastReceiveTime(currentDate.getTime());
            this.chatSessionMapper.insertOrUpdate(chatSession);

            ChatSessionUser chatSessionUser = new ChatSessionUser();
            chatSessionUser.setSessionId(sessionId);
            chatSessionUser.setUserId(applyUserId);
            chatSessionUser.setContactId(contactId);
            UserInfo contactUser = userInfoMapper.selectByUserId(contactId);
            chatSessionUser.setContactName(contactUser.getNickName());
            chatSessionUserList.add(chatSessionUser);

            ChatSessionUser contactSessionUser = new ChatSessionUser();
            contactSessionUser.setSessionId(sessionId);
            contactSessionUser.setUserId(contactId);
            contactSessionUser.setContactId(applyUserId);

            UserInfo applyUserInfo = userInfoMapper.selectByUserId(applyUserId);
            contactSessionUser.setContactName(applyUserInfo.getNickName());
            chatSessionUserList.add(contactSessionUser);

            this.chatSessionUserMapper.insertOrUpdateBatch(chatSessionUserList);

            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum.ADD_FRIEND.getType());
            chatMessage.setMessageContent(applyInfo);
            chatMessage.setSendUserId(applyUserId);
            chatMessage.setSendUserNickName(applyUserInfo.getNickName());
            chatMessage.setSendTime(currentDate.getTime());
            chatMessage.setContactId(contactId);
            chatMessage.setContactType(UserContactTypeEnum.USER.getType());
            this.chatMessageMapper.insert(chatMessage);

            MessageSendDto messageSendDto = CopyTools.copy(chatMessage, MessageSendDto.class);
            messageHandler.sendMessage(messageSendDto);

            messageSendDto.setMessageType(MessageTypeEnum.ADD_FRIEND_SELF.getType());
            messageSendDto.setContactId(applyUserId);
            messageSendDto.setExtendData(contactUser);
            messageHandler.sendMessage(messageSendDto);
        } else {
            // 加入群组
            ChatSessionUser chatSessionUser = new ChatSessionUser();
            chatSessionUser.setSessionId(sessionId);
            chatSessionUser.setUserId(contactId);
            chatSessionUser.setContactId(contactId);
            GroupInfo groupInfo = this.groupInfoMapper.selectByGroupId(contactId);
            chatSessionUser.setContactName(groupInfo.getGroupName());
            this.chatSessionUserMapper.insertOrUpdate(chatSessionUser);

            UserInfo applyUserInfo = userInfoMapper.selectByUserId(applyUserId);
            String sendMessage = String.format(MessageTypeEnum.ADD_FRIEND_SELF.getInitMessage(), applyUserInfo.getNickName());

            ChatSession chatSession = new ChatSession();
            chatSession.setSessionId(sessionId);
            chatSession.setLastMessage(sendMessage);
            chatSession.setLastReceiveTime(currentDate.getTime());
            this.chatSessionMapper.insertOrUpdate(chatSession);

            // 增加聊天消息
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setSessionId(sessionId);
            chatMessage.setMessageType(MessageTypeEnum.ADD_GROUP.getType());
            chatMessage.setMessageContent(sendMessage);
//			chatMessage.setSendUserId(applyUserId);
//			chatMessage.setSendUserNickName(applyUserInfo.getNickName());
            chatMessage.setSendTime(currentDate.getTime());
            chatMessage.setContactId(contactId);
            chatMessage.setContactType(UserContactTypeEnum.GROUP.getType());
            chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
            this.chatMessageMapper.insert(chatMessage);


            // 将群组添加到联系人
            redisComponent.addUserContact(applyUserId, groupInfo.getGroupId());

            // 添加群组到群组频道
            channelContextUtils.addUser2Group(applyUserId, groupInfo.getGroupId());

            MessageSendDto messageSendDto = CopyTools.copy(chatMessage, MessageSendDto.class);

            UserContactQuery query = new UserContactQuery();
            query.setContactId(contactId);
            query.setStatus(UserContactStatusEnum.FRIEND.getCode());
            Integer memberCount = this.userContactMapper.selectCount(query);
            messageSendDto.setMemberCount(memberCount);
            messageSendDto.setContactId(contactId);
            messageSendDto.setContactName(groupInfo.getGroupName());
            messageHandler.sendMessage(messageSendDto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addContact4Robot(String userId) {
        Date curDate = new Date();
        SysSettingDto sysSettingDto = redisComponent.getSysSetting();
        String contactId = sysSettingDto.getRobotUid();
        String contactName = sysSettingDto.getRobotNickName();
        String sendMessage = sysSettingDto.getRobotWelcome();
        sendMessage = StringUtils.cleanHtmlTag(sendMessage);

        // 添加机器人为好友
        UserContact userContact = new UserContact();
        userContact.setUserId(userId);
        userContact.setContactId(contactId);
        userContact.setContactName(contactName);
        userContact.setContactType(UserContactTypeEnum.USER.getType());
        userContact.setStatus(UserContactStatusEnum.FRIEND.getCode());
        userContact.setCreateTime(curDate);
        userContact.setLastUpdateTime(curDate);
        this.userContactMapper.insert(userContact);

        // 增加会话信息
        String sessionId = StringUtils.getChatSessionId4User(new String[]{userId, contactId});
        ChatSession chatSession = new ChatSession();
        chatSession.setLastMessage(sendMessage);
        chatSession.setSessionId(sessionId);
        chatSession.setLastReceiveTime(curDate.getTime());
        this.chatSessionMapper.insert(chatSession);

        // 增加会话人信息
        ChatSessionUser chatSessionUser = new ChatSessionUser();
        chatSessionUser.setSessionId(sessionId);
        chatSessionUser.setUserId(userId);
        chatSessionUser.setContactId(contactId);
        chatSessionUser.setContactName(contactName);
        this.chatSessionUserMapper.insert(chatSessionUser);

        // 增加聊天消息
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSessionId(sessionId);
        chatMessage.setMessageType(MessageTypeEnum.CHAT.getType());
        chatMessage.setMessageContent(sendMessage);
        chatMessage.setSendUserId(contactId);
        chatMessage.setSendUserNickName(contactName);
        chatMessage.setSendTime(curDate.getTime());
        chatMessage.setContactId(userId);
        chatMessage.setContactType(UserContactTypeEnum.USER.getType());
        chatMessage.setStatus(MessageStatusEnum.SENDED.getStatus());
        this.chatMessageMapper.insert(chatMessage);
    }
}